package com.ang.utils;

import java.io.*;

public class MySerializable {

    /**
     * @Title: getObjFromStr
     * @Description: 将字符串反序列化成对象
     * @param serStr
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     * @throws ClassNotFoundException    设定文件
     * @return Object    返回类型
     * @throws
     */
    public static Object getObjFromStr(String serStr) throws UnsupportedEncodingException, IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        Object obj = null;
        try {
            String redStr = java.net.URLDecoder.decode(serStr, "UTF-8");
            byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            obj = objectInputStream.readObject();
        } catch (Exception e) {
            throw e;
        } finally {
            objectInputStream.close();
            byteArrayInputStream.close();
        }
        return obj;
    }

    /**
     * @Title: getStrFromObj
     * @Description: 将对象序列化成字符串
     * @param obj
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException    设定文件
     * @return String    返回类型
     * @throws
     */
    public static String getStrFromObj(Serializable obj) throws IOException, UnsupportedEncodingException {
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        String serialStr = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            serialStr = byteArrayOutputStream.toString("ISO-8859-1");
            serialStr = java.net.URLEncoder.encode(serialStr, "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            objectOutputStream.close();
            byteArrayOutputStream.close();
        }
        return serialStr;
    }
}
